package com.adwin.addcoin.ui.main

import android.app.Application
import android.media.MediaDataSource
import android.util.Log
import android.widget.Toast
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.adwin.addcoin.repository.SchedulerTransformer
import com.adwin.addcoin.repository.api.TestApi
import com.adwin.addcoin.repository.bean.HomeTaskBean
import com.adwin.addcoin.repository.bean.UserInfoBean
import com.adwin.addcoin.repository.net.RetrofitClient
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import org.json.JSONObject

class PersonalCenterModel(application: Application):AndroidViewModel(application) {
    val userInfoBean = MutableLiveData<UserInfoBean>()
    var taskLists = MutableLiveData<ArrayList<HomeTaskBean>>()
    var isRefresh = MutableLiveData(false)
    var isLoad = MutableLiveData(false)
    var pageSize = 15
    fun getUserInfo(){
        viewModelScope.launch {
            RetrofitClient.getInstance().getService(TestApi::class.java).getUserInfo().compose(
                SchedulerTransformer()
            ).subscribe({
                if (it.isSuccessful){
                    val bean = it.body()?.data
                    if (bean != null) {
                        userInfoBean.value = bean!!
                    }
                }
            },{

            })
        }
    }

    /**
     * 获取活动任务列表
     */
    fun getTaskList(pageNumber:Int){
        isRefresh.value = true
        val json = JSONObject()
        json.put("pageNum",pageNumber)
        json.put("pageSize",pageSize)
        json.put("status",1)
        val requestBody: RequestBody = MultipartBody.create(MediaType.get("application/json;charset=utf-8"), json.toString())
        RetrofitClient.getInstance().getService(TestApi::class.java)
            .getTaskList(requestBody).compose(
                SchedulerTransformer()
            ).subscribe({
                if (it.isSuccessful){
                    it.body()?.let { data ->
                        if (data.code == 200){
                            if (pageNumber == 1){
                                taskLists.value?.clear()
                            }
                            val lists = ArrayList<HomeTaskBean>()
                            taskLists.value?.let {
                                lists.addAll(it)
                                isLoad.value = it.size >= pageNumber
                            }

                            if (data.data!=null){
                                lists.addAll(data.data.list)
                                taskLists.value = lists
                            }
                        }
                    }
                }
                isRefresh.value = false
            },{
                isRefresh.value = false
                Log.d("taskError","error:${it.message}")
            })
    }
}